import { AfterViewInit, Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { debounceTime } from 'rxjs/operators';
import { PermitConfig, PermitConfigId } from '../../../models';
import { BidOpeningComponent } from '../bid-opening/bid-opening.component';

@Component({
  selector: 'zepride-bid-opening-ceremony',
  templateUrl: './bid-opening-ceremony.component.html',
  styleUrls: ['./bid-opening-ceremony.component.less', '../field.common.less', '../bid-opening/bid-opening.component.less']
})
export class BidOpeningCeremonyComponent extends BidOpeningComponent implements OnInit, AfterViewInit, OnDestroy {
  dm: any = {};
  curBgImgUrl;
  isfullscreen = false;
  curTabItem: any = {};
  voices = [];

  playObj = {
    status: '',
    playing: false,
    rate: 1,
    voiceName: 'Microsoft Huihui - Chinese (Simplified, PRC)'
  };
  permitConfig: PermitConfig[] = [
    { mode: 'query', permitId: '查看', permitName: '', authObjectId: '' },
    { mode: 'edit', permitId: '编辑', permitName: '', authObjectId: '' }
  ];
  editModeStatus: any = {};
  isAuthorized = true;
  @ViewChild('bidOpenCeremonyRef') bidOpenCeremonyRef: ElementRef<HTMLDivElement>;

  ngOnInit() {
    this.getVoices();

    this.timer = 'off';
    super.ngOnInit();

    this.dm || (this.dm = {});
    this.buildTabContent();
  }

  ngAfterViewInit() {
    setTimeout(() => {
      const authData = this.setAuthorityData();
      this.zeprideAuthorityData = {
        ...authData,
        afterChecked: this.afterAuthChecked.bind(this)
      };
    }, 0);
    this.registerModelChange();
  }

  buildTabContent() {
    if (this.dm.tabContents && this.dm.tabContents.length) {
      this.curTabItem = this.dm.tabContents[0];
      this.curTabItem.selected = true;

      for (const tabCotentItem of this.dm.tabContents) {
        tabCotentItem.sourceBodyTxt = tabCotentItem.sourceBodyTxt ? tabCotentItem.sourceBodyTxt : tabCotentItem.bodyTxt;
        tabCotentItem.bodyTxt = this.replaceTxt(tabCotentItem.spaceChars, tabCotentItem.sourceBodyTxt);
      }
    } else {
      this.dm.tabContents = [];
    }
  }

  private replaceTxt(spaceChars, txt) {
    if (spaceChars) {
      for (const item of spaceChars) {
        item.value = this.dataModel[item.bindField];
        let repTxt = item.value;
        repTxt || (repTxt = '【】');
        txt = txt.replace(item.code, repTxt);
      }
    }

    return txt;
  }

  selectTab(item) {
    this.dm.tabContents.map(x => x.selected = false);
    this.curTabItem = item;
    this.curTabItem.selected = true;
  }

  play() {
    let div = document.createElement('div');
    div.innerHTML = this.curTabItem.bodyTxt;
    let readTxt = div.innerText;

    if (readTxt) {
      const utterance = new SpeechSynthesisUtterance(readTxt);
      utterance.rate = this.playObj.rate;
      utterance.voice = this.voices.find(x => x.name == this.playObj.voiceName);
      if (this.playObj.status == 'pause') {
        speechSynthesis.resume();
      }
      else if (this.playObj.status == '') {
        speechSynthesis.speak(utterance);
      }
      this.playObj.status = 'playing';

      // this.playObj.playing = !this.playObj.playing;

      utterance.onend = () => {
        // this.playObj.playing = !this.playObj.playing;
        this.playObj.status = '';
      };
    }
  }

  stopPlay() {
    speechSynthesis.cancel();
    this.playObj.status = '';
  }

  pausePlay() {
    speechSynthesis.pause();
    this.playObj.status = 'pause';
  }

  getVoices() {
    this.voices = speechSynthesis.getVoices();
    this.voices = this.voices.filter(x => x.lang == 'zh-CN');
  }

  editMode(key: string) {
    if (!this.isAuthorized) {
      return;
    }
    this.editModeStatus[key] = true;
  }

  cancelEdit(key: string) {
    this.editModeStatus[key] = false;
  }

  reset() {
    if (this.playObj) {
      this.playObj.rate = 1;
      this.playObj.voiceName = 'Microsoft Huihui - Chinese (Simplified, PRC)';
    }
    else {
      this.playObj = {
        status: '',
        playing: false,
        rate: 1,
        voiceName: 'Microsoft Huihui - Chinese (Simplified, PRC)'
      };
    }
  }

  toggleFullScreen() {
    const isFullscreen = document.fullscreenElement;
    const element = this.bidOpenCeremonyRef;
    if (element && element.nativeElement) {
      if (isFullscreen) {
        document.exitFullscreen();
      } else {
        element.nativeElement.requestFullscreen();
      }
    }
  }

  afterAuthChecked(params: {
    permitId: PermitConfigId;
    isAuthorized: boolean;
  }) {
    if (!params.isAuthorized) {
      this.isAuthorized = false;
    }
  }

  registerModelChange() {
    this.modelChange$ = this.engineService.dataModelChange$.pipe(
      debounceTime(50)
    ).subscribe(data => {
      if (data.identifyId !== this.componentData.identifyId) {
        this.buildTabContent();
      }
    });
  }

  ngOnDestroy() {
    if (this.modelChange$) {
      this.modelChange$.unsubscribe();
    }
  }
}
